<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>

    function updateView(key, value, newValue) {
      console.log('视图更新', key, value, newValue);
    }

    function observeArray(target) {
      let originArrayPrototype = Array.prototype
      const customArrayPrototype = Object.create(Array.prototype)
      const ArrayFunc = ['push', 'pop', 'splice', 'unshift']

      ArrayFunc.forEach(func => {
        customArrayPrototype[func] = function () {
          updateView()
          originArrayPrototype[func].call(this, ...arguments)
        }
      })
      target.__proto__ = customArrayPrototype
    }

    function defineReactive(target, key, value) {
      observe(value)
      Object.defineProperty(target, key, {
        get() {
          return value
        },
        set(newValue) {
          if (newValue !== value) {
            observe(value)
            updateView(key, value, newValue)
            value = newValue
          }
        }
      })
    }

    function observe(target) {
      if (typeof target !== 'object' || target === null) {
        return target
      }

      if (Array.isArray(target)) {
        observeArray(target)
      }

      for (let k in target) {
        defineReactive(target, k, target[k])
      }
    }

    let data = {
      a: 1,
      b: {
        name: '宝冶'
      },
      c: [1, 2, 3],
      d: [{ a: 1 }, { b: 2 }]
    }

    observe(data)
  </script>
</body>

</html>